package com.dmagic.cms.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dmagic.cms.common.dao.CommonDao;
import com.dmagic.cms.common.exception.ServiceException;
import com.dmagic.cms.common.exception.ValidateException;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.service.CommonService;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.dao.NewsDao;
import com.dmagic.cms.entity.LinkedHeatMap;
import com.dmagic.cms.entity.News;
import com.dmagic.cms.service.HeatMapService;
import com.dmagic.cms.service.NewsService;

@Service
@Transactional(readOnly = true, rollbackFor = ValidateException.class)
public class NewsServiceImpl extends CommonService<News> implements NewsService {
	@Autowired
	private NewsDao newsDao;

	@Autowired
	private HeatMapService heatMapService;

	@Override
	protected CommonDao<News, Serializable> getCommonDao() {
		return (CommonDao) newsDao;
	}

	@Override
	@Transactional(readOnly = false)
	public void saveNews(News[] news) throws ValidateException {
		for (News n : news) {
			if (StringUtil.isBlank(n.getNewsTitle()) && StringUtil.isBlank(n.getNewsContent())) {
				continue;
			}
			if (n.getIsTop() == null) {
				n.setIsTop(false);
			}
			if (n.getNewsStatus() == null) {
				n.setNewsStatus(false);
			}
			saveEntity(n);
		}
	}

	@Override
	public void searchNews(PageUtil<Map> pageUtil) throws ServiceException {
		try {
			newsDao.searchNews(pageUtil);
		} catch (Exception e) {
			throw new ServiceException(e);
		}
	}

	@Override
	public News getNews(Long newsId) throws ServiceException {
		return getEntityById(newsId);
	}

	public List<News> getNewsByNewsNo(String newsNo) {
		return newsDao.findBy("newsNo", newsNo);
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteNews(List<Long> newsIds) throws ServiceException {
		for (Long newsId : newsIds) {
			deleteNews(newsId);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void deleteNews(Long newsId) throws ServiceException {
		deleteEntityById(newsId);
		heatMapService
				.deleteLinkedHeatMapByLinkedIdAndType(newsId, LinkedHeatMap.HeatMapType.news.getValue());
	}
}
